<script setup>
import { onMounted, ref, watch } from "vue";
import { useUserStore } from '@/stores/userStore'
import InfoCard from "@/components/InfoCard.vue";
import { userLoginApi } from '@/apis/user.js';
import { workListApi } from '@/apis/work.js';
import { onLoad, onShow } from "@dcloudio/uni-app";
import {useWorkStore} from '@/stores/workStore.js';
const workStore = useWorkStore()
// const workList = ref([{ text: "1",id: 1,username: "1" }, { text: "2",id: 2,username: "2"  }, { text: "3",id: 3,username: "3"  }, { text: "4",id: 4,username: "4"  }]);
const workList = ref([])
const userStore = useUserStore()
const dataInit = async()=>{
  // 从pinia拿 pinia如果有那就不管了
  const user = userStore.getUserInfo()
  if(user){
  }else{
    // pinia没有就通过token发送给后端获取
    // 没有token的话无法显示该页面
    const userRes = userLoginApi()
    userStore.setUserInfo(userRes.data)
  }

  const work = workStore.getWorkInfo()
  if(work){
    workList.value = work
  }else{
    const workRes = await workListApi()
    if(workRes.code === 200){
      workStore.setWorkInfo(workRes.data)
      workList.value = workRes.data
    }
  }
}
// 获取数据
onLoad(async()=>{
  dataInit()
})

onShow(async () => {
  dataInit()
  // const work = workStore.getWorkInfo()
  // if(work){
  //   workList.value = work
  // }else{
  //   const res = await workListApi()
  //   if(res.code === 200){
  //     workStore.setWorkInfo(res.data)
  //     workList.value = res.data
  //   }
  // }

})

// 创建一个深度监听器来监听 workList 的变化
watch(() => workList.value.length, (newVal, oldVal) => {
    if(newVal > 0){
      dataFlag.value = true
    }else{
      dataFlag.value = false
    }
}, {
    deep: true // 设置 deep 为 true 来深度监听数组或对象内部的变化
});
const dataFlag = ref(false)
</script>
<template>
  
  <view class="uni-flex">
    <!-- 首页大家的作品 -->
    <view v-for="(item, index) in workList" class="single-card" v-if="dataFlag" :key="index">
      <InfoCard :workInfo="item" class="infoCard"></InfoCard>
    </view>
    <view class="single-card" v-else>
      暂无数据~
    </view>
  </view>
  
</template>

<style lang="scss">
.uni-flex {
  margin-top: 5rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}


.single-card {
  width:50%; // 减去卡片之间的间距
  // background-color: red;
  $uni-shadow-lg:0px 1px 10px 2px rgba($color: #a5a4a4, $alpha: 0.5);
}

.infoCard {
  width: 40%;
}
</style>
